package cn.hamster3.mc.plugin.core.bukkit.command.lore.sub;

import cn.hamster3.mc.plugin.core.bukkit.command.ChildCommand;
import cn.hamster3.mc.plugin.core.bukkit.constant.CoreMessage;
import cn.hamster3.mc.plugin.core.bukkit.util.CoreBukkitUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class LoreFlagCommand extends ChildCommand {
    public static final LoreFlagCommand INSTANCE = new LoreFlagCommand();

    private LoreFlagCommand() {
    }

    @Override
    public @NotNull String getName() {
        return "flag";
    }

    @Override
    public @NotNull String getUsage() {
        return "flag <ItemFlag>";
    }

    @Override
    public boolean hasPermission(@NotNull CommandSender sender) {
        return true;
    }

    @Override
    public @NotNull String getDescription() {
        return "为手持物品设置 flag";
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
        if (args.length < 1) {
            CoreMessage.COMMAND_LORE_FLAG_NOT_INPUT.show(sender);
            return true;
        }
        if (!(sender instanceof Player)) {
            CoreMessage.COMMAND_MUST_USED_BY_PLAYER.show(sender);
            return true;
        }
        Player player = (Player) sender;
        ItemStack stack = player.getItemInHand();
        if (CoreBukkitUtils.isEmptyItemStack(stack)) {
            CoreMessage.COMMAND_LORE_HAND_EMPTY.show(player);
            return true;
        }
        ItemFlag flag;
        try {
            flag = ItemFlag.valueOf(args[0]);
        } catch (IllegalArgumentException e) {
            CoreMessage.COMMAND_LORE_FLAG_SET_ERROR_INPUT.show(player);
            return true;
        }

        ItemMeta meta = stack.getItemMeta();
        if (meta != null) {
            if (meta.hasItemFlag(flag)) {
                meta.removeItemFlags(flag);
                CoreMessage.COMMAND_LORE_FLAG_REMOVE_SUCCESS.show(player, "%flag%", flag.name());
            } else {
                meta.addItemFlags(flag);
                CoreMessage.COMMAND_LORE_FLAG_SET_SUCCESS.show(player, "%flag%", flag.name());
            }
        }
        stack.setItemMeta(meta);

        return true;
    }

    @Override
    public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) {
        return Arrays.stream(ItemFlag.values())
                .map(Enum::name)
                .filter(o -> o.startsWith(args[0].toUpperCase()))
                .collect(Collectors.toList());
    }
}
